package com.agileai.bpm.manager;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;

import com.agileai.domain.DataRow;
import com.agileai.util.CryptionUtil;

public class PropertiesResourceManager {
	public static final String SecretKey = "agileai!";
	public static final String BPMConfigsKey = "bpms";
	
	private static PropertiesResourceManager instance = null;
	private HashMap<String,LinkedHashMap<String,String>> propertiesConfig = new HashMap<String,LinkedHashMap<String,String>>();
	
	private PropertiesResourceManager(){
		
	}
	
	public static synchronized PropertiesResourceManager instance(){
		if (instance == null){
			instance = new PropertiesResourceManager();
		}
		return instance;
	}
	
	public void init(List<DataRow> masterRecords,HashMap<String,List<DataRow>> entries){
		if (masterRecords != null && entries != null){
			for (int i=0;i < masterRecords.size();i++){
				DataRow row = masterRecords.get(i);
				String varId = row.getString("VAR_ID");
				List<DataRow> records = entries.get(varId);
				this.initPropertiesConfig(row, records);
			}
		}
	}
	
	public void refreshProperties(DataRow row,List<DataRow> entries){
		this.initPropertiesConfig(row, entries);
	}
	
	private void initPropertiesConfig(DataRow row,List<DataRow> entries){
		if (row != null && entries != null && entries.size() > 0){
			String varCode = row.stringValue("VAR_CODE");
			HashMap<String,String> configRow = getConfigRow(varCode);
			
			for (int i=0;i < entries.size();i++){
				DataRow tempRow = entries.get(i);
				String entryCode = tempRow.getString("ENTRY_CODE");
				String isCrypt = tempRow.getString("ENCRIPTION");
				String entryValue = tempRow.getString("ENTRY_VALUE");
				
				if ("Y".equals(isCrypt)){
					configRow.put(entryCode,CryptionUtil.decryption(entryValue, SecretKey));
				}else{
					configRow.put(entryCode, entryValue);
				}
			}
		}
	}
	
	private HashMap<String,String> getConfigRow(String varCode){
		if (propertiesConfig.containsKey(varCode)){
			return propertiesConfig.get(varCode);
		}else{
			LinkedHashMap<String,String> tempRow = new LinkedHashMap<String,String>();
			propertiesConfig.put(varCode, tempRow);
			return tempRow;
		}
	}
	
	
	public HashMap<String,LinkedHashMap<String,String>> getPropertiesConfig(){
		return propertiesConfig;
	}
	
	public String getConfigProperty(String section,String key){
		String result = null;
		HashMap<String,LinkedHashMap<String,String>> allProperties = getPropertiesConfig();
		LinkedHashMap<String,String> properties = allProperties.get(section);
		if (properties != null){
			result = properties.get(key);
		}
		return result;
	}
	
	public String getConfigProperty(String section,String key,String defaultValue){
		String result = getConfigProperty(section, key);
		if (result == null){
			result = defaultValue;
		}
		return result;
	}	
}
